﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using DomainModel;
using Services.Abstract;

namespace Web
{
    public partial class Daybook : BasePage
    {
        public IUserService UserService { get; set; }
        public IDateTimeService DateTimeService { get; set; }
        public ISemesterService SemesterService { get; set; }
        public IStudyYearService StudyYearService { get; set; }
        public ILessonService LessonService { get; set; }
        public IWorkTypeService WorkTypeService { get; set; }
        public IPermissionService PermissionService { get; set; }

        protected StudySemester SelectedSemester;
        protected User SelectedStudent;
        protected int SelectedWeek = 0;

        private List<User> _students;
        private List<StudyYear> _studyYears;

        protected new void Page_Load(object sender, EventArgs e)
        {
            SelectMenuItem("NavDaybook");

            _students = UserService.GetUsers(Role.Student).OrderBy(s => s.UserProfile.Fio).ToList();
            _studyYears = StudyYearService.GetAll().OrderBy(sy => sy.BeginDate).ToList();

            if (User.IsInRole(Role.Student.ToString()))
            {
                SelectedStudent = UserService.GetUserByLogin(User.Identity.Name);
            }
            else if (User.IsInRole(Role.Parent.ToString()))
            {
                var currentUser = UserService.GetUserByLogin(User.Identity.Name);
                SelectedStudent = currentUser.Child;
            }
            else
            {
                try
                {
                    long studentId = long.Parse(Request.QueryString["StudentId"]);
                    SelectedStudent = UserService.GetById(studentId);
                }
                catch (ArgumentNullException) { }
                catch (FormatException) { }
                if (SelectedStudent == null)
                    SelectedStudent = _students.First();
            }

            if (!PermissionService.CanViewDaybook(SelectedStudent))
            {
                Response.Redirect("/Error/AccessDenied.aspx");
            }

            try
            {
                long semesterId = long.Parse(Request.QueryString["SemesterId"]);
                SelectedSemester = SemesterService.GetById(semesterId);
            }
            catch (ArgumentNullException) { }
            catch (FormatException) { }
            if (SelectedSemester == null)
                SelectedSemester = SemesterService.GetCurrentSemester();

            try
            {
                SelectedWeek = int.Parse(Request.QueryString["WeekNo"]);
            }
            catch (ArgumentNullException) { }
            catch (FormatException) { }
            if (SelectedWeek == 0)
                SelectedWeek = DateTimeService.GetWeekNoByCurrentDay(SelectedSemester, DateTime.Now);

            if (!IsPostBack)
            {
                BindDdlSemesters();
                BindDdlStudents();

                SetPrevNextWeekLinks();

                DdlSemesters.Items.FindByValue(SelectedSemester.Id.ToString()).Selected = true;
                DdlStudents.Items.FindByValue(SelectedStudent.Id.ToString()).Selected = true;

                BindListViewDaybookWeek();
            }
        }

        private void BindDdlSemesters()
        {
            var ds = new List<object>();

            foreach (var studyYear in _studyYears)
            {
                int semesterNo = 1;
                foreach (var semester in studyYear.StudySemesters)
                {
                    ds.Add(new
                    {
                        Id = semester.Id,
                        Name = studyYear.Name + " (" + semesterNo + "-й семестр)",
                    });
                    semesterNo++;
                }
            }

            DdlSemesters.DataSource = ds;
            DdlSemesters.DataValueField = "Id";
            DdlSemesters.DataTextField = "Name";
            DdlSemesters.DataBind();
        }

        private void BindDdlStudents()
        {
            var ds = new List<object>();

            foreach (var student in _students)
            {
                ds.Add(new
                           {
                               Id = student.Id,
                               Fio = student.UserProfile.Fio,
                           });
            }

            DdlStudents.DataSource = ds;
            DdlStudents.DataValueField = "Id";
            DdlStudents.DataTextField = "Fio";
            DdlStudents.DataBind();
        }

        private void SetPrevNextWeekLinks()
        {
            string url = string.Format("/Daybook.aspx?SemesterId={0}&StudentId={1}&WeekNo=", SelectedSemester.Id, SelectedStudent.Id);

            if (SelectedWeek == 1)
                LinkPrevWeek.Enabled = false;
            else
                LinkPrevWeek.NavigateUrl = url + (SelectedWeek - 1).ToString();

            LinkNextWeek.NavigateUrl = url + (SelectedWeek + 1).ToString();
        }

        private void BindListViewDaybookWeek()
        {
            var ds = new List<object>();

            DateTime weekBeginDate, weekEndDate;
            DateTimeService.GetWeekBeginAndEndDate(SelectedSemester, SelectedWeek, out weekBeginDate, out weekEndDate);

            int daysCount = weekEndDate.Day - weekBeginDate.Day;
            for (int dayNo = 1; dayNo <= daysCount; dayNo++)
            {
                var date = weekBeginDate.AddDays(dayNo - 1);
                ds.Add(new
                {
                    DayNo = dayNo,
                    DayName = date.DayOfWeek.ToString(),
                    DateFormatted = date.ToString("yyyy-MM-dd"),
                    Date = date.ToShortDateString(),
                });
            }

            ListViewDaybookWeek.DataSource = ds;
            ListViewDaybookWeek.DataBind();
        }

        protected void ListViewDaybookWeek_OnItemDataBound(object sender, ListViewItemEventArgs e)
        {
            var dataKey = ListViewDaybookWeek.DataKeys[e.Item.DisplayIndex];
            if (dataKey == null)
            {
                ShowSysMsg("Возникла непредвиденная ошибка.");
                return;
            }

            string dayNoStr = dataKey.Value.ToString();
            int dayNo = int.Parse(dayNoStr);

            var listViewDaybookDay = (ListView)e.Item.FindControl("ListViewDaybookDay");

            DateTime weekBeginDate, weekEndDate;
            DateTimeService.GetWeekBeginAndEndDate(SelectedSemester, SelectedWeek, out weekBeginDate, out weekEndDate);

            var lessons = LessonService.GetLessons(SelectedStudent, weekBeginDate.AddDays(dayNo - 1));

            var ds = new List<object>();

            foreach (var lesson in lessons)
            {
                ds.Add(new
                           {
                               PairNo = lesson.TimetableUnit.PairNo,
                               SubjectName = lesson.TimetableUnit.Subject.Name,
                               SubjectType = WorkTypeService.GetWorkTypeName(lesson.TimetableUnit.WorkType),
                               Homework = "Какое-то домашнее задание",
                               Mark = lesson.Mark,
                           });
            }

            listViewDaybookDay.DataSource = ds;
            listViewDaybookDay.DataBind();
        }

        protected void DdlSemesters_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            string url = string.Format("/Daybook.aspx?SemesterId={0}&StudentId={1}", DdlSemesters.SelectedValue, SelectedStudent.Id);

            Response.Redirect(url);
        }

        protected void DdlStudents_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            string url = string.Format("/Daybook.aspx?SemesterId={0}&StudentId={1}", SelectedSemester.Id, DdlStudents.SelectedValue);

            Response.Redirect(url);
        }
    }
}